package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 处理用户搜索词,将用户的搜索关键词CRUD到MongoDB中
 */
@Slf4j
@Service
@Transactional
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 保存用户的搜索关键字记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async  //标记该方法为异步方法
    public void insert(String keyword, Integer userId) {

        //1.根据用户id和关键词查询该用户的搜索关键词记录
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearche = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.判断是否存在当前关键词, a.如果存在 更新创建时间
        if (apUserSearche != null) {
            apUserSearche.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearche);
            return;
        }

        //3. b.如果不存在  ①判断历史记录的总数, 总数小于10 直接存入  ②历史记录总数大于10,替换存入时间最早的那条记录
        apUserSearche = new ApUserSearch();
        apUserSearche.setUserId(userId);
        apUserSearche.setKeyword(keyword);
        apUserSearche.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC, "createTime"));
        List<ApUserSearch> apUserSearchList =
                mongoTemplate.find(query1, ApUserSearch.class);

        if (apUserSearchList == null || apUserSearchList.size() < 10) {
            //直接存入
            mongoTemplate.save(apUserSearche);
        } else {
            //替换掉最后一条记录
            ApUserSearch lastUserSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastUserSearch.getUserId())), apUserSearche);
        }
    }


    /**
     * 查询用户关键词搜索历史记录
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //Threadlocal获取当前登录用户的id
        Integer userId = ApUserThreadLocalUtil.getUser().getId();
        if (userId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<ApUserSearch> apUserSearchList =
                mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                                .with(Sort.by(Sort.Direction.DESC, "createdTime")),
                        ApUserSearch.class);

        return ResponseResult.okResult(apUserSearchList);
    }


    /**
     * 删除用户的搜索关键词记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1.入参校验
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        if (ApUserThreadLocalUtil.getUser().getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.删除
        mongoTemplate.remove(Query.query(Criteria.where("id").is(dto.getId())), ApUserSearch.class);
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
